/*
 * SocketTest.cpp
 *
 *  Created on: 2014-1-5
 *      Author: zhao
 */
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

#define MAXLINE 4096

int main222(int argc,char **argv)
{
	int listenfd,connfd;
	struct sockaddr_in servaddr;
	char buff[MAXLINE];
	int n;
	if((listenfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1 )
	{
		cout<<"can't start socket "<<endl;
		exit(1);
	}
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	const char *ip = "127.0.0.1";
	inet_aton(ip,&(servaddr.sin_addr));
	servaddr.sin_port = htons(6666);
	if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1)
	{
		cout<<"bind error :"<<strerror(errno)<<endl;
		exit(1);
	}
	if(listen(listenfd,100) == -1)
	{
		cout<<"listen error :"<<strerror(errno)<<endl;
		exit(1);
	}
	cout<<"waiting for connection "<<endl;
	while(true)
	{
		connfd = accept(listenfd,(struct sockaddr*)NULL,NULL);
		if(connfd == -1)
		{
			cout<<"accetp socket error :"<<strerror(errno)<<"error num:"<<errno<<endl;
		}
		cout<<"one connect "<<endl;
		int opts = fcntl(connfd,F_GETFL);
		fcntl(connfd,opts|O_NONBLOCK);
		n = read(connfd,buff,MAXLINE);
		buff[n] = '\0';
		cout<<"receive buff:"<<buff<<endl;
		close(connfd);
	}

	return 0;
}
